package com.example.xiaoxueqixiangmu.jiemian;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.xiaoxueqixiangmu.MyFragmentActivity;
import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.bean.Order;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class chepiaoyuding5Activity extends AppCompatActivity {
    private TextView txtBack , txtTitle , txtDetail ;
    private ImageView imgER;
    private static final String TAG = "chepiaoyuding5Activity";
    private ArrayList<String> paArray , numberArray ;
    private Order order;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chepiaoyuding5);

        // Layout中组件的初始化
        txtBack = findViewById(R.id.txtBack);
        txtDetail = findViewById(R.id.txtDetail);
        imgER = findViewById(R.id.imgER);
        orderId = getIntent().getStringExtra("orderId");
        txtDetail.setText("您的订单"+orderId+"支付成功，可以凭此二维码办理取票业务，也可以在订单中查看相关信息及二维码");

        // 向服务器提交支付订单的信息，获取服务器返回的数据并将数据加载到二维码中
        queryFromServer();

        // 从上一个页面中获取乘客列表，车票数量，订单对象 数据
        paArray = getIntent().getStringArrayListExtra("paArray");
        numberArray = getIntent().getStringArrayListExtra("numberArray");
        order = (Order)getIntent().getSerializableExtra("order");

        // 返回键的点击事件，点击跳转到主页面
        txtBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(chepiaoyuding5Activity.this, MyFragmentActivity.class);
                startActivity(intent);
            }
        });

        // ActiongBar上返回键的显示
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setDisplayHomeAsUpEnabled(true);
    }

    //返回键的点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch ( item.getItemId() ){
            case android.R.id.home:
                chepiaoyuding5Activity.this.finish();
                break;
        }
        return true;
    }

    // 从服务器提交支付订单的方法，向服务器中传入乘客人员信息，乘车车次，购买车票的数量。
    public void queryFromServer(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient okHttpClient = new OkHttpClient();
                SharedPreferences sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
                String JSESSIONID = sharedPreferences.getString("cookie", "");
                FormBody formBody =new FormBody.Builder()
                        .add("orderId","20213Yt")
                        .build();
                Request request = new Request.Builder().url(Constant.Host +"/otn/Pay").post(formBody).addHeader("cookie",JSESSIONID).build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response response = call.execute();
                    String string = response.body().string();
                    Log.i(TAG, "run: response: "+string);

                    // 二维码生成的代码，从服务器获取到数据后 加载到二维码中进行展示
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            QRCodeUtils qrCodeUtils = new QRCodeUtils();
                            qrCodeUtils.generateQrcodeAndDisplay(paArray.toString()+"  "+numberArray.toString()+"  "+order.toString(),imgER);
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }


    //  原先指导书中的代码，项目中并没有用到
    public static void createQRImage(String data, ImageView ivQrcode, int QR_WIDTH, int QR_HEIGHT) {
          try {
               Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
               hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
               BitMatrix bitMatrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, QR_WIDTH,QR_HEIGHT, hints);
               int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
               for (int y = 0; y < QR_HEIGHT; y++) {
                    for (int x = 0; x < QR_WIDTH; x++) {
                         if (bitMatrix.get(x, y)) {
                              pixels[y * QR_WIDTH + x] = 0xff000000;
                             } else {
                              pixels[y * QR_WIDTH + x] = 0xffffffff;
                             }
                        }
                      }
                Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                Bitmap.Config.ARGB_8888);
                 bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
                 ivQrcode.setImageBitmap(bitmap);
                } catch (WriterException e) {
                 e.printStackTrace();
          }
         }
    private String orderId = "20213Yt";

}